package com.example.quartz;


import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.matchers.EverythingMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class QuarztUtils {

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private JobListenerServer jobListenerServer;

    private static int num=0;



    /**
     * 添加rest调用
     */
    public void addQuartz(SysJob job){

        String clazz=job.getClazz();

        try {
            if(num==0){
                num++;
                scheduler.clear();
            }
            //添加执行监听器
            scheduler.getListenerManager().addJobListener(jobListenerServer, EverythingMatcher.allJobs());

            scheduler.start();
            JobDetail jobDetail;
            JobDataMap jobDataMap=new JobDataMap();

            jobDataMap.put("sysjob",job);

            //如果是rest,则添加附带执行url
            jobDetail= JobBuilder.newJob(getClass(clazz).getClass()).withIdentity(clazz,job.getJobgroup())
                    .usingJobData(jobDataMap) //添加url
                    .build();

            // 表达式调度构建器(即任务执行的时间)
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCron());

            // 按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(clazz,job.getJobgroup()).withSchedule(scheduleBuilder).build();
            scheduler.scheduleJob(jobDetail,trigger);
            log.info(job.getJobgroup()+"任务添加成功");
        }catch (Exception e){
            log.info(job.getJobgroup()+"添加失败 失败信息如下 "+e.getMessage());
        }
    }

    public void startAll(){
        try {
            scheduler.resumeAll();
        }catch (Exception e){
            log.info("启动失败信息如下"+e.getMessage());
            e.printStackTrace();
        }
        log.info("启动所有rest任务成功");
    }

    /**
     * 暂停所有任务
     */
    public void stopAll(){
        try {
            scheduler.pauseAll();
        }catch (Exception e){
            e.getMessage();
        }
    }





    /**
     * 任务暂停
     */
    public void stopQuarzt(SysJob sysJob) {
        try {
            String clazz= sysJob.getClazz();
            String group= sysJob.getJobgroup();
            scheduler.pauseJob(JobKey.jobKey(clazz,group));
            sysJob.setStatus(1);
        }catch (Exception e){
            e.printStackTrace();
            sysJob.setStatus(0);
        }
        sysJob.setStatus(0);
    }



    /**
     * 任务恢复
     */
    public void startQuarzt(SysJob sysJob) {
        String clazz= sysJob.getClazz();
        try {
            String group= sysJob.getJobgroup();
            scheduler.resumeJob(JobKey.jobKey(clazz,group));
            sysJob.setStatus(0);
        }catch (Exception e){
            e.printStackTrace();
            sysJob.setStatus(1);
        }
        sysJob.setStatus(0);
    }

    /**
     * 任务删除
     */
    public void deleteQuarzt(SysJob sysJob) {
        try {
            String group= sysJob.getJobgroup();
            String clazz= sysJob.getClazz();
            scheduler.pauseTrigger(TriggerKey.triggerKey(clazz,group));  //暂停
            scheduler.unscheduleJob(TriggerKey.triggerKey(clazz,group));
            scheduler.deleteJob(JobKey.jobKey(clazz,group));
            sysJob.setStatus(3);
        }catch (Exception e){
            e.printStackTrace();
            sysJob.setStatus(1);
        }
        sysJob.setStatus(0);
    }



    /**
     * 返回类路径
     * @param
     * @return
     */
    private String returnClass(SysJob sysJob){
        String clazz= sysJob.getClazz();
        String type= sysJob.getType();

        if("3".equals(type)){
            clazz=RestJob.class.getName();
        }
        return clazz;
    }


    /**
     * 更改任务
     */
    public void updataQuarzt(SysJob job) {
        try {
            String group=job.getJobgroup();
            String cron=job.getCron();
            String clazz=job.getClazz();

            TriggerKey triggerKey = TriggerKey.triggerKey(clazz,group);
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);

            // 按新的cronExpression表达式重新构建trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
            // 按新的trigger重新设置job执行
            scheduler.rescheduleJob(triggerKey, trigger);
        }catch (Exception e){
            job.setStatus(1);
            e.printStackTrace();
        }
        job.setStatus(0);

    }


    private static QuartzJobBean getClass(String classname) throws Exception {
        Class<?> class1 = Class.forName(classname);
        return (QuartzJobBean) class1.newInstance();
    }
}
